package com.sgb.goods.view.activity;

import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.sgb.goods.BR;
import com.sgb.goods.R;
import com.sgb.goods.databinding.GoodsActivityGoodsSpecBinding;
import com.sgb.goods.entity.GetSkuEntity1;
import com.sgb.goods.entity.GoodsPublishSkuListEntity;
import com.sgb.goods.entity.GoodsSkuChild1;
import com.sgb.goods.utils.Constants;
import com.sgb.goods.utils.base.BaseActivity;
import com.sgb.goods.view.adapter.GoodsSpecAdapter;
import com.sgb.goods.view.adapter.SpecPriceAdapter;
import com.sgb.goods.viewmodel.GoodsSpecViewModel;
import com.sgb.goods.viewmodel.publish.GoodsPublishViewModel2;
import com.swgk.core.dialog.RoundCornerDialog;
import com.swgk.core.util.MToast;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Route(path = Constants.ARouter.AR_GOODS_SPEC)
public class GoodsSpecActivity extends BaseActivity<GoodsActivityGoodsSpecBinding, GoodsSpecViewModel> {
    
    private GoodsSpecAdapter goodsSpecAdapter;
    private SpecPriceAdapter specPriceAdapter;
    private HashSet<String> checkFlagList = new HashSet<>();
    private List<GetSkuEntity1> skuEntities;
    private List<GoodsPublishSkuListEntity> combinationData;
    private List<GoodsPublishSkuListEntity> combinationSet;
    private List<GoodsPublishSkuListEntity> combinationOld;
    //被选中的集合
    private List<List<GoodsSkuChild1>> aggregate;
    private String cid3;

    private List<GoodsPublishSkuListEntity> selectList;
    public GoodsPublishViewModel2 goodsPublishViewModel;

    @Override
    protected int getLayoutResId() {
        return R.layout.goods_activity_goods_spec;
    }

    @Override
    protected void initViewModel() {
        mViewModel = createViewModel(GoodsSpecViewModel.class, BR.viewModel);
        goodsPublishViewModel = createViewModel(GoodsPublishViewModel2.class);
    }

    @Override
    protected void init() {
        selectList = new ArrayList<>();
        combinationData = new ArrayList<>();
        combinationSet = new ArrayList<>();
        combinationOld = new ArrayList<>();
        aggregate = new ArrayList<>();

        combinationSet = getIntent().getParcelableArrayListExtra("combination");
        getCheckFlagListById();

        cid3 = getIntent().getStringExtra("cid3");

        mViewModel.getSku(cid3);

        mDataBinding.head.ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mDataBinding.head.title.setText("商品规格");

        goodsSpecAdapter = new GoodsSpecAdapter();
        LinearLayoutManager gridLayoutManager = new LinearLayoutManager(this);
        mDataBinding.rvCheck.setAdapter(goodsSpecAdapter);
        mDataBinding.rvCheck.setLayoutManager(gridLayoutManager);
        goodsSpecAdapter.onItemChildCLickListener(new GoodsSpecAdapter.ItemChildCLickListener() {
            @Override
            public void checkArr(Map<Integer, Set<Integer>> map, int position) {
                int allSize = 1;
                GoodsPublishSkuListEntity addData = null;
                combinationData.clear();
                aggregate.clear();
                // 获取键集合的迭代器
                Iterator it = map.keySet().iterator();
                while (it.hasNext()) {
                    int next = (int) it.next();
                    if (map.get(next).size() != 0) {
                        allSize = map.get(next).size() * allSize;
                        setArrItem(map.get(next), next);
                    }
                }
                for (int i = 0; i < allSize; i++) {
                    addData = new GoodsPublishSkuListEntity();
                    combinationData.add(addData);
                }
                selectList.clear();
                getSelectList(aggregate, aggregate.get(0), new ArrayList<GoodsSkuChild1>());
                for (int j = 0; j < combinationData.size(); j++) {
                    combinationData.get(j).list = selectList.get(j).list;
                }
                specPriceAdapter.setNewData(combinationData);
            }

            @Override
            public void addDefaultPriceData() {
                GoodsPublishSkuListEntity addData = new GoodsPublishSkuListEntity();
                addData.isFill = true;
                combinationData.add(addData);
                specPriceAdapter.setNewData(combinationData);
            }

            @Override
            public void deleteAll() {
                combinationData.clear();
                specPriceAdapter.setNewData(combinationData);
            }
        });
        LinearLayoutManager gridLayoutManager2 = new LinearLayoutManager(this);
        specPriceAdapter = new SpecPriceAdapter();
        mDataBinding.rvPl.setAdapter(specPriceAdapter);
        mDataBinding.rvPl.setLayoutManager(gridLayoutManager2);
    }

    @Override
    protected void initObserve() {
        mViewModel.skuListLD.observe(this, skuList -> {
            isSku(skuList);
        });
    }

    public void isSku(List<GetSkuEntity1> data) {
        skuEntities = data;
        if (data != null && data.size() != 0) {
            //循环设置全部不选中
            for (int i = 0; i < data.size(); i++) {
                data.get(i).isSelect = "1";
                for (int j = 0; j < data.get(i).list.size(); j++) {
                    data.get(i).list.get(j).setOnClick(false);
                }
            }
            //循环设置已选中
            for (String valId : checkFlagList) {
                for (int i = 0; i < data.size(); i++) {
                    for (int j = 0; j < data.get(i).list.size(); j++) {
                        if (valId.equals(data.get(i).list.get(j).getValId())) {
                            data.get(i).list.get(j).setOnClick(true);
                            data.get(i).isSelect = "0";
                        }
                    }
                }
            }
            goodsSpecAdapter.setNewData(data);
            String isFill = skuIsFill(data);
            if ("".equals(isFill) && checkFlagList.size() == 0) {
                GoodsPublishSkuListEntity addData = new GoodsPublishSkuListEntity();
                if (combinationSet != null && combinationSet.size() == 1) {
                    if (combinationSet.get(0).list == null || combinationSet.get(0).list.size() == 0) {
                        addData.money = combinationSet.get(0).money;
                    }
                }
                combinationData.clear();
                addData.isFill = true;
                combinationData.add(addData);
                specPriceAdapter.setNewData(combinationData);
            } else {
                specPriceAdapter.setNewData(combinationSet);
            }
        }
    }

    private String skuIsFill(List<GetSkuEntity1> data) {
        for (int i = 0; i < data.size(); i++) {
            if ("1".equals(data.get(i).isFill)) {
                if (!isHaveClick(data.get(i).list)) {
                    return data.get(i).paramData;
                }
            }
        }
        return "";
    }


    private boolean isHaveClick(List<GoodsSkuChild1> itemData) {
        for (int i = 0; i < itemData.size(); i++) {
            if (itemData.get(i).isOnClick()) {
                return true;
            }
        }
        return false;
    }

    @Override
    protected void initListener() {
        mDataBinding.tvPl.setOnClickListener(v -> {
            if (specPriceAdapter.getData().size() != 0) {
                showETextDialog();
            } else {
                MToast.showToast(GoodsSpecActivity.this, "请先选择规格");
            }
        });

        mDataBinding.nextView.setOnClickListener(v -> {
            if (specPriceAdapter.getData().size() != 0) {
                if (!"".equals(skuIsFill(goodsSpecAdapter.getData()))) {
                    MToast.showToast(GoodsSpecActivity.this, "请勾选商品规格");
                    return;
                }
                List<GoodsPublishSkuListEntity> newList = specPriceAdapter.getData();
                if (isFillMoney(newList)) {
                    List<GoodsPublishSkuListEntity> oldList = combinationOld;
                    if (oldList != null) {
                        for (int h = 0; h < newList.size(); h++) {
                            for (int j = 0; j < oldList.size(); j++) {
                                GoodsPublishSkuListEntity oldEntity = oldList.get(j);
                                GoodsPublishSkuListEntity newEntity = newList.get(h);
                                StringBuffer oldString = new StringBuffer();
                                StringBuffer newString = new StringBuffer();
                                for (int a = 0; a < oldEntity.list.size(); a++) {
                                    oldString.append(oldEntity.list.get(a).getValId());
                                }
                                for (int b = 0; b < newEntity.list.size(); b++) {
                                    newString.append(newEntity.list.get(b).getValId());
                                }
                                if (oldString.toString().equals(newString.toString())) {
                                    newEntity.id = oldEntity.id;
                                    newEntity.vipMaxPrice = oldEntity.vipMaxPrice;
                                }
                            }
                        }
                    }
                    if (isRightPrice(newList)) {
                        //goodsPublishViewModel.combination.setValue(newList);
                        finish();
                    }
                }
            } else {
                MToast.showToast(GoodsSpecActivity.this, "请先选择规格");
            }
        });
    }

    private boolean isRightPrice(List<GoodsPublishSkuListEntity> newList) {
        for (int i = 0; i < newList.size(); i++) {
            if (!TextUtils.isEmpty(newList.get(i).money) && !TextUtils.isEmpty(newList.get(i).vipMaxPrice)) {
                BigDecimal money = new BigDecimal(newList.get(i).money);
                BigDecimal vipMaxPrice = new BigDecimal(newList.get(i).vipMaxPrice);
                if (money.compareTo(vipMaxPrice) == -1) {
                    //销售价小于会员价
                    MToast.showToast(GoodsSpecActivity.this, "销售价不能低于会员价");
                    return false;
                }
            }
        }
        return true;
    }

    private boolean isFillMoney(List<GoodsPublishSkuListEntity> newList) {
        for (int i = 0; i < newList.size(); i++) {
            if (newList.get(i).money == null || "".equals(newList.get(i).money)) {
                MToast.showToast(GoodsSpecActivity.this, "请填写完整单价");
                return false;
            }
        }
        return true;
    }

    //取出所有选中的值
    private void setArrItem(Set<Integer> set, int position) {
        List<GoodsSkuChild1> select = new ArrayList<>();
        for (int i = 0; i < skuEntities.size(); i++) {
            if (position == i) {
                Iterator it = set.iterator();
                while (it.hasNext()) {
                    select.add(skuEntities.get(position).list.get((Integer) it.next()));
                }
                aggregate.add(select);
            }
        }
    }

    List<GoodsSkuChild1> arr2 = new ArrayList<>();

    public void getSelectList(List<List<GoodsSkuChild1>> list, List<GoodsSkuChild1> arr, List<GoodsSkuChild1> str) {
        for (int i = 0; i < list.size(); i++) {
            //取得当前的数组bai
            if (i == list.indexOf(arr)) {
                //迭代du数组
                for (GoodsSkuChild1 st : arr) {
                    arr2.clear();
                    List<GoodsSkuChild1> temp = new ArrayList<>();
                    temp.add(st);
                    temp.addAll(str);
                    arr2.addAll(temp);
                    if (i < list.size() - 1) {
                        getSelectList(list, list.get(i + 1), temp);
                    } else if (i == list.size() - 1) {
                        GoodsPublishSkuListEntity goodsPublishSkuListEntity = new GoodsPublishSkuListEntity();
                        for (int k = 0; k < arr2.size(); k++) {
                            goodsPublishSkuListEntity.list.add(arr2.get(k));
                        }
                        selectList.add(goodsPublishSkuListEntity);
                    }
                }
            }
        }
    }

    private void showETextDialog() {
        View view = View.inflate(this, R.layout.goods_dialog_set_price, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(this, 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);
        EditText et_content = view.findViewById(R.id.et_content);
        TextView tv_logout_confirm = view.findViewById(R.id.tv_logout_confirm);
        TextView tv_logout_cancel = view.findViewById(R.id.tv_logout_cancel);
        //确定
        tv_logout_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (combinationData.size() != 0) {
                    for (int i = 0; i < combinationData.size(); i++) {
                        combinationData.get(i).money = et_content.getText().toString();
                    }
                }
                specPriceAdapter.setNewData(combinationData);
                roundCornerDialog.dismiss();
            }
        });
        //取消
        tv_logout_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                roundCornerDialog.dismiss();
            }
        });
    }

    public HashSet<String> getCheckFlagListById() {
        checkFlagList.clear();
        for (int i = 0; i < combinationSet.size(); i++) {
            for (int j = 0; j < combinationSet.get(i).list.size(); j++) {
                checkFlagList.add(combinationSet.get(i).list.get(j).getValId());
            }
        }
        return checkFlagList;
    }

}